// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.assets.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelData;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.assets.service.AssetsDepartmentService;
import com.liuxinlong.modules.dao.AssetsDepartmentDao;
import com.liuxinlong.modules.dao.PatentDepartmentDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.AssetsDepartment;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 费用维护管理业务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2024-01-11
 */
@Service
@Slf4j
public class AssetsDepartmentServiceImpl implements AssetsDepartmentService {

    @Autowired
    private AssetsDepartmentDao assetsDepartmentDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PatentDepartmentDao patentDepartmentDao;

    @Override
    @Transactional
    public List<Map<String, Object>> pageAssetsDepartmentInfo(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<AssetsDepartment> originalList = assetsDepartmentDao.pageAssetsDepartmentInfo(queryParam);
        List<Map<String, Object>> resultList = completeResult(originalList, startNum);
        return resultList;
    }

    @Override
    public int getAssetsDepartmentInfoCount(Map<String, Object> queryParam) {
        return assetsDepartmentDao.getAssetsDepartmentInfoCount(queryParam);
    }

    @Override
    @Transactional
    public void addAssetsDepartmentInfo(AssetsDepartment assetsDepartment) {
        String id = SnowFlake.nextIdStr();
        assetsDepartment.setId(id);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        assetsDepartment.setCreateUser(currentUser.getId());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        assetsDepartment.setCreateTime(currentTime);
        assetsDepartmentDao.insert(assetsDepartment);
    }

    @Override
    @Transactional
    public void updateAssetsDepartmentInfo(AssetsDepartment assetsDepartment) {
        String id = assetsDepartment.getId();
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改固资部门信息失败，固资部门信息不存在！");
        }
        AssetsDepartment oldInfo = assetsDepartmentDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改固资部门信息失败，固资部门信息不存在！");
        }
        assetsDepartment.setCreateTime(oldInfo.getCreateTime());
        assetsDepartment.setCreateUser(oldInfo.getCreateUser());
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        assetsDepartment.setUpdateUser(currentUser.getId());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        assetsDepartment.setUpdateTime(currentTime);
        assetsDepartmentDao.updateById(assetsDepartment);
    }

    @Override
    @Transactional
    public void deleteAssetsDepartmentInfo(String id) {
        AssetsDepartment assetsDepartment = assetsDepartmentDao.selectById(id);
        if (ObjectUtils.isEmpty(assetsDepartment)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，固资部门信息不存在！");
        }
        assetsDepartmentDao.deleteById(id);
    }

    @Override
    public void exportAssetsDepartment(Map<String, Object> queryParam, HttpServletResponse response) {
        ExcelData data = new ExcelData();
        data.setFileName("固资部门导出excel.xlsx");
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<AssetsDepartment> assetsDepartmentList = assetsDepartmentDao.pageAssetsDepartmentInfo(queryParam);
        Map<String, Map<String, String>> departmentMap = patentDepartmentDao.getDepartmentMap();
        Map<String,Map<String,String>> userMap = userDao.getUserMap();
        String[] head = {"序号", "部门名称", "部门代码", "部门负责人"};
        data.setHead(head);
        String[][] dataList = new String[assetsDepartmentList.size()][head.length];
        int index = 0;
        for (AssetsDepartment assetsDepartment : assetsDepartmentList) {
            dataList[index][0] = String.valueOf(index + 1);
            dataList[index][1] = departmentMap.get(assetsDepartment.getDepartment()).get("name");
            dataList[index][2] = assetsDepartment.getDepartmentSn();
            String manager = departmentMap.get(assetsDepartment.getDepartment()).get("manage");
            dataList[index][3] = userMap.containsKey(manager) ? userMap.get(manager).get("name") : "";
            index++;
        }
        data.setData(Arrays.asList(dataList));
        ExcelUtils.exportExcel(response, data);
    }

    /**
     * 补全数据
     *
     * @param originalList 原始数据
     * @param startNum     数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<AssetsDepartment> originalList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String,Map<String,String>> userMap = userDao.getUserMap();
        Map<String,Map<String,String>> departmentMap = patentDepartmentDao.getDepartmentMap();
        int sort = startNum + 1;
        for (AssetsDepartment assetsDepartment : originalList) {
            Map<String, Object> item = ObjectUtils.object2Map(assetsDepartment);
            item.put("sort", sort);
            if (departmentMap.containsKey(assetsDepartment.getDepartment())) {
                Map<String,String> patentDep = departmentMap.get(assetsDepartment.getDepartment());
                item.put("departmentName",patentDep.get("name"));
                item.put("manageName",userMap.containsKey(patentDep.get("manage")) ? userMap.get(patentDep.get("manage")).get("name") : "");
            } else {
                item.put("departmentName","");
                item.put("manageName","");
            }
            resultList.add(item);
            sort++;
        }
        return resultList;
    }
}
